package com.df.tv.launcher.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.df.tv.launcher.R;
import com.df.tv.tm.aidl.AppInfoEntity;
import com.telecom.tv189.comlib.view.XUtilsImageView;

public class ApplicationAdapter extends BaseAdapter {
    private Context mContext;
    public List<AppInfoEntity> mAppList = new ArrayList<AppInfoEntity>();

    public int[] mAppBackgroundImgResources = new int[] { R.drawable.app_bg1, R.drawable.app_bg2, R.drawable.app_bg3,
            R.drawable.app_bg4, R.drawable.app_bg5, R.drawable.app_bg6, R.drawable.app_bg7, R.drawable.app_bg8,
            R.drawable.app_bg9, R.drawable.app_bg10 };

    public ApplicationAdapter(Context context, List<AppInfoEntity> list) {
        this.mContext = context;
        this.mAppList = list;
    }

    @Override
    public int getCount() {
        return mAppList.size();
    }

    @Override
    public Object getItem(int position) {
        return mAppList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void notifySetDataChanged(List<AppInfoEntity> appList) {
        this.mAppList = appList;
        this.notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        AppInfoEntity appBean = null;
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.griditem, null);
            holder.name = (TextView) convertView.findViewById(R.id.tv_app_name);
            holder.img = (XUtilsImageView) convertView.findViewById(R.id.img_app);
            convertView.setTag(holder);

        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        appBean = mAppList.get(position);
        setImageView(position, holder.img, appBean, false);

        if (appBean.isLocalApp()) {
            holder.name.setVisibility(View.VISIBLE);
            holder.name.setText(TextUtils.isEmpty(appBean.getAppname()) ? "Default App" : appBean.getAppname());
        }
        else {
            holder.name.setVisibility(View.INVISIBLE);
        }
        return convertView;
    }

    private static class ViewHolder {
        XUtilsImageView img;
        TextView name;
    }

    private Bitmap bitmap = null;
    private Canvas canvas = new Canvas();
    private Drawable mIconBackground;
    private Drawable srcIcon;
    private final Rect oldBounds = new Rect();
    private HashMap<String, Integer> mTempStoredBgMap = new HashMap<String, Integer>();
    private HashMap<String, Bitmap> mTempStoredBitMap = new HashMap<String, Bitmap>();
    private HashMap<String, Bitmap> mTempStoredFocusBitMap = new HashMap<String, Bitmap>();

    private int bgLeft = (BitmapComparm.BITMAP_CANVAS_WIDTH - BitmapComparm.APPLICATION_WIDTH) / 2;
    private int bgTop = (BitmapComparm.BITMAP_CANVAS_HEIGTH - BitmapComparm.APPLICATION_HEIGHT) / 2;

    private int iconTop = bgTop + BitmapComparm.APP_TITLE_ICON_OFFSET_HEIGHT;
    private int iconLeft = bgLeft + BitmapComparm.APPLICATION_WIDTH - BitmapComparm.APP_TITLE_ICON_WIDTH
            - BitmapComparm.APP_TITLE_ICON_OFFSET_WIDTH;

    /**
     * Create normal app display bitmap.
     * 
     * @param appIcon
     * @param pName
     * @return
     */
    public Bitmap createImageBitmap(Bitmap appIcon, String pName) {
        if (mTempStoredBitMap.get(pName) != null) {
            bitmap = mTempStoredBitMap.get(pName);
            return bitmap;
        }

        Random random = new Random();
        int index = random.nextInt(10);
        mTempStoredBgMap.put(pName, Integer.valueOf(index));
        mIconBackground = mContext.getResources().getDrawable(mAppBackgroundImgResources[index]);

        bitmap = Bitmap.createBitmap(BitmapComparm.BITMAP_CANVAS_WIDTH, BitmapComparm.BITMAP_CANVAS_HEIGTH,
                Bitmap.Config.ARGB_8888);
        canvas.setBitmap(bitmap);
        canvas = drawBgForCanvas(bgLeft, bgTop);

        srcIcon = adjustAppIcon(appIcon);

        srcIcon.setBounds(iconLeft, iconTop, iconLeft + BitmapComparm.APP_TITLE_ICON_WIDTH, iconTop
                + BitmapComparm.APP_TITLE_ICON_HEIGHT);
        srcIcon.draw(canvas);
        srcIcon.setBounds(oldBounds);

        mTempStoredBitMap.put(pName, bitmap);
        return bitmap;
    }

    /**
     * Create focus app display bitmap.
     * 
     * @param appIcon
     * @param pName
     * @return
     */
    public Bitmap createFocusImageBitmap(Bitmap appIcon, String pName) {
        if (mTempStoredFocusBitMap.get(pName) != null) {
            bitmap = mTempStoredFocusBitMap.get(pName);
            return bitmap;
        }
        mIconBackground = mContext.getResources().getDrawable(mAppBackgroundImgResources[mTempStoredBgMap.get(pName)]);

        bitmap = Bitmap.createBitmap(BitmapComparm.BITMAP_CANVAS_WIDTH, BitmapComparm.BITMAP_CANVAS_HEIGTH,
                Bitmap.Config.ARGB_8888);
        canvas.setBitmap(bitmap);
        canvas = drawBgForCanvas(bgLeft, bgTop);

        srcIcon = adjustAppIcon(appIcon);

        float focusWidthRatio = BitmapComparm.APPLICATION_FOCUS_WIDTH / (float) BitmapComparm.APPLICATION_WIDTH;
        float focusHeightRatio = BitmapComparm.APPLICATION_FOCUS_HEIGHT / (float) BitmapComparm.APPLICATION_HEIGHT;
        srcIcon.setBounds(iconLeft - (int) (iconLeft * (focusWidthRatio - 1) / 2), iconTop, iconLeft
                - (int) (iconLeft * (focusHeightRatio - 1) / 2)
                + (int) (BitmapComparm.APP_TITLE_ICON_WIDTH * focusWidthRatio), iconTop
                + (int) (BitmapComparm.APP_TITLE_ICON_WIDTH * focusWidthRatio));

        srcIcon.draw(canvas);
        srcIcon.setBounds(oldBounds);
        mTempStoredFocusBitMap.put(pName, bitmap);
        return bitmap;
    }

    /**
     * Adjust app icon size to fix application display interface.
     * 
     * @param src
     * @return
     */
    private Drawable adjustAppIcon(Bitmap src) {

        Matrix matrix = getMatrixToCreateNewBitmap(src);
        Bitmap newBitmap = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);

        BitmapDrawable bd = new BitmapDrawable(newBitmap);
        srcIcon = bd;
        oldBounds.set(srcIcon.getBounds());

        return srcIcon;
    }

    /**
     * Prepare background for cavas.
     * 
     * @param left
     * @param top
     * @return
     */
    private Canvas drawBgForCanvas(int left, int top) {
        // 画背景图
        if (mIconBackground != null) {
            mIconBackground.setBounds(left, top, left + BitmapComparm.APPLICATION_WIDTH, top
                    + BitmapComparm.APPLICATION_HEIGHT);
            mIconBackground.draw(canvas);
        }
        return canvas;
    }

    /**
     * Get matrix to create new Bitmap.
     * 
     * @param top
     * @param left
     * @param appIcon
     * @return
     */
    private Matrix getMatrixToCreateNewBitmap(Bitmap appIcon) {
        // 获得缩放图标比例
        Matrix matrix = new Matrix();
        float widthRatio = BitmapComparm.APP_TITLE_ICON_HEIGHT / (float) appIcon.getWidth();
        float heightRatio = BitmapComparm.APP_TITLE_ICON_WIDTH / (float) appIcon.getHeight();
        matrix.postScale(widthRatio, heightRatio);

        return matrix;

    }

    /**
     * Set App display imageview.
     * 
     * @param position
     * @param xImageView
     * @param appEntity
     */
    public void setImageView(int position, XUtilsImageView xImageView, AppInfoEntity appEntity, boolean isFocus) {
        //		xImageView.setImageResource(R.drawable.app_bg1);

        if (appEntity.getIconBitmap() != null) {
            xImageView.setScaleType(ScaleType.CENTER);
            //			if (!isFocus) {
            xImageView.setImageBitmap(createImageBitmap(appEntity.getIconBitmap(),
                    TextUtils.isEmpty(appEntity.getApkname()) ? "Default apk" : appEntity.getApkname()));
            //			}
            /*else {
            	xImageView.setImageBitmap(createFocusImageBitmap(appEntity.getIconBitmap(), TextUtils.isEmpty(appEntity.getApkname()) ? "Default apk" : appEntity.getApkname()));
            }*/
            return;
        }

        if (!TextUtils.isEmpty(appEntity.getImg2())) {
            xImageView.setScaleType(ScaleType.FIT_XY);
            xImageView.setImage(appEntity.getImg2());
            return;
        }

        if (!TextUtils.isEmpty(appEntity.getImg1())) {
            xImageView.setScaleType(ScaleType.FIT_XY);
            xImageView.setImage(appEntity.getImg1());
            return;
        }

    }

    /**
     * Final comparam for draw bitmap.
     * 
     * @author pc1
     * 
     */
    private interface BitmapComparm {
        public static final int APP_TITLE_ICON_WIDTH = 60;
        public static final int APP_TITLE_ICON_HEIGHT = 60;

        public static final int BITMAP_CANVAS_WIDTH = 250;
        public static final int BITMAP_CANVAS_HEIGTH = 250;

        public static final int APP_TITLE_ICON_OFFSET_WIDTH = 50;
        public static final int APP_TITLE_ICON_OFFSET_HEIGHT = 50;

        public static final int APPLICATION_WIDTH = 220;
        public static final int APPLICATION_HEIGHT = 220;

        public static final int APPLICATION_FOCUS_WIDTH = 260;
        public static final int APPLICATION_FOCUS_HEIGHT = 260;

    }
}
